// Grant Foster
// gfoster5

#include "Parser.h"

bool listOn = false;
bool symbolsOn = false;

/*
The main function starts things off. It requires an input and an output file
to be specified. There are two optional flags; they are "-symbols" and "list".
Appropriate exit procedures are written to respond to improper input.
*/
int main(int argc, char *argv[])
{
	if (argc == 3)
	{
		FILE *inputFile;
		FILE *outputFile;

		inputFile = fopen(argv[1], "r");
		outputFile = fopen(argv[2], "w");

		if (inputFile == NULL)
		{
			printf("Cannot open \"%s\"\n", argv[1]);
			exit(EXIT_FAILURE);
		}

		// first step: remove all comments from input file
		FILE *CommentsRemovedWrite = fopen("CommentsRemoved", "w");  
		removeComments(inputFile, CommentsRemovedWrite);
		fclose(CommentsRemovedWrite);

		FILE *CommentsRemovedRead = fopen("CommentsRemoved", "r"); 

		// second step: prepare asm file for parsing
		FILE *CommandReadyWrite = fopen("CommandReady", "w");
		prepareCommands(CommentsRemovedRead, CommandReadyWrite);
		fclose(CommandReadyWrite);

		FILE *CommandReadyRead = fopen("CommandReady", "r");
		
		// parse commands and write to output file
		commandParser(CommandReadyRead, outputFile);

		remove("CommentsRemoved");
		remove("CommandReady");
		fclose(outputFile);
	}

	else if (argc == 4)
	{

		if (strcmp(argv[1], "-symbols") && strcmp(argv[1], "-list"))
		{
			printf("Wrong arguments!\nYou put \"%s\" instead of", argv[1]);
			printf(" \"-symbols\" or \"-list\".\n");
			remove(argv[3]); // cleans up new "write" file
			exit(EXIT_FAILURE);
		}

		FILE *inputFile;
		FILE *outputFile;

		inputFile = fopen(argv[2], "r");
		outputFile = fopen(argv[3], "w");

		if (inputFile == NULL)
		{
			printf("Cannot open \"%s\"\n", argv[2]);
			exit(EXIT_FAILURE);
		}

		// first step: remove all comments from input file
		FILE *CommentsRemovedWrite = fopen("CommentsRemoved", "w");  
		removeComments(inputFile, CommentsRemovedWrite);
		fclose(CommentsRemovedWrite);

		FILE *CommentsRemovedRead = fopen("CommentsRemoved", "r"); 

		// second step: prepare asm file for parsing
		FILE *CommandReadyWrite = fopen("CommandReady", "w");
		prepareCommands(CommentsRemovedRead, CommandReadyWrite);
		fclose(CommandReadyWrite);

		FILE *CommandReadyRead = fopen("CommandReady", "r");

		if (!strcmp(argv[1], "-symbols"))
		{	
			symbolsOn = true;
			fprintf(outputFile, "Address\t\tSymbol\n");
			fprintf(outputFile, "--------------------------------\n");
		}
		else if (!strcmp(argv[1], "-list"))
		{
			listOn = true;
		}

		commandParser(CommandReadyRead, outputFile);

		remove("CommentsRemoved");
		remove("CommandReady");
		fclose(outputFile);
	}

	else
	{
		printf("Wrong number of arguments!\n");
		exit(EXIT_FAILURE);
	}
	
	return 0;
}
